package chapter_3.client;

import chapter_3.message.coder.TextMessageCoder;
import chapter_3.message.entity.RequestMessage;
import chapter_3.message.entity.ResponseMessage;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.*;
import java.util.Arrays;

/**
 * 创建一个投票UDP客户端，向客户端发送投票请求和查询请求，从接收到的数据中解析出对应的信息
 */
public class VoteUDPClient {
    public static void main(String[] args) throws IOException {
        int port = 9090;
        InetAddress address = InetAddress.getByName("127.0.0.1");
        System.out.println(address.getHostAddress().toString());
        DatagramSocket socket = new DatagramSocket();

        //创建一个投票信息，并发送,采用字符编码
        int candidateId = 100;
        RequestMessage voteMessage = new RequestMessage(false,candidateId);
        TextMessageCoder msgCoder = new TextMessageCoder();
        byte[] msgByteArray = msgCoder.toWire(voteMessage);

        DatagramPacket MsgPacket = new DatagramPacket(msgByteArray,msgByteArray.length,address,port);
        System.out.println("----------------发送投票信息-------------");
        System.out.println("投票给候选人: "+candidateId);
        socket.send(MsgPacket);

        //创建一个查询消息
        voteMessage = new RequestMessage(true,candidateId);
        msgByteArray = msgCoder.toWire(voteMessage);
        MsgPacket.setData(msgByteArray);
        System.out.println("-------------------发送查询消息------------------");
        System.out.println("查询候选人: "+candidateId+" 的票数");
        socket.send(MsgPacket);
        //接收服务器返回的消息

        MsgPacket = new DatagramPacket(new byte[TextMessageCoder.MESSAGE_MAX_LENGTH],TextMessageCoder.MESSAGE_MAX_LENGTH);
        //设置接收数据的最长阻塞时间（10s),超过时间抛出异常
        socket.setSoTimeout(10000);
        boolean receiveFlag = true;
        do {
            try {
                socket.receive(MsgPacket);
            }catch(InterruptedIOException e){
                System.out.println("-------------------消息接收完毕-------------------");
                receiveFlag = false;
            }
            System.out.println("----------------开始接收消息-------------------------");
            //如果正常接收到数据，就对数据解码
            byte[] receiveMsgBytes = Arrays.copyOfRange(MsgPacket.getData(),0,MsgPacket.getLength());
            ResponseMessage responseMessage = (ResponseMessage) msgCoder.fromWire(receiveMsgBytes);
            System.out.println("接收到的消息类型"+ (responseMessage.getInquiryFlag()?"查询响应":"投票响应"));
            System.out.println("候选人: "+responseMessage.getCandidate().getId());
            System.out.println("候选人票数: "+responseMessage.getCandidate().getVoteNumber());
            System.out.println("---------------------------------");
        }while(receiveFlag);
        socket.close();



    }

}
